<template>
  <div>
    <div class="pay-ment">
      <div class="">
        实际应支付({{ modelComputed }}) = 发票清单({{payComputed}})
      </div>
      <div>
        <el-button plain type="single-number" @click="addLine">
          新增行
        </el-button>
        <el-button plain type="single-number" @click="copyLine">
          复制行
        </el-button>
        <el-button plain type="single-number" @click="deleteRow">
          删除行
        </el-button>
      </div>
    </div>
    <!-- <div class="ccui-multifunctional-table-wrapper"> -->
    <el-group-title class="ccui-group-wrapper">
      <template slot="groupTitle">
        <el-form
          :model="form"
          label-width="160px"
          class="ccui-form"
          style="overflow: visible"
        >
          <el-table
            :data="tableData"
            style="margin-bottom: 20px; width: 100%"
            class="ccui-form-child-table"
            border
            @selection-change="selectionLineChangeHandle"
            :header-cell-class-name="must"
            lazy
            ref="tableList"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column label="序号" type="index" width="55" fixed />
            <el-table-column
              :show-overflow-tooltip="true"
              prop="changeValue"
              label="变动"
              width="200"
            >
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.changeValue"
                  disabled
                  placeholder="请选择"
                  @change="changeVal(scope.row)"
                >
                  <el-option
                    v-for="item in changeValueOptions"
                    :key="item.dicKey"
                    :label="item.dicValue"
                    :value="item.dicValue"
                  >
                  </el-option>
                </el-select>
              </template>
            </el-table-column>

            <el-table-column
              :show-overflow-tooltip="true"
              prop="paymentNameValue"
              label="款项名称"
              width="200"
            >
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.paymentNameValue"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in options"
                    :key="item.id"
                    :label="item.name"
                    :value="item.name"
                  >
                  </el-option>
                </el-select>
              </template>
            </el-table-column>

            <el-table-column
              :show-overflow-tooltip="true"
              prop="specialProjectValue"
              label="专项项目"
              width="150"
            >
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.specialProjectValue"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in options"
                    :key="item.id"
                    :label="item.name"
                    :value="item.name"
                  >
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              :show-overflow-tooltip="true"
              prop="receivablePayableNo"
              label="应收应付编号"
              width="200"
              align="right"
              header-align="left"
            >
              <template slot-scope="scope">
                <el-input
                  disabled
                  width="200"
                  v-model="scope.row.receivablePayableNo"
                >
                </el-input>
              </template>
            </el-table-column>

            <el-table-column
              :show-overflow-tooltip="true"
              prop="unWrittenOffOriginalAmount"
              label="未核销金额（原币）"
              width="200"
              align="right"
              header-align="left"
            >
              <template slot-scope="scope">
                <el-input
                  disabled
                  v-model="scope.row.unWrittenOffOriginalAmount"
                />
              </template>
            </el-table-column>

            <el-table-column
              :show-overflow-tooltip="true"
              prop="originalCurrencyValue"
              label="原币币种"
              width="200"
              align="right"
              header-align="left"
            >
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.originalCurrencyValue"
                  placeholder="请选择"
                  @change="changeOriginalCurrency(scope.row)"
                >
                  <el-option
                    v-for="item in originalCurrencyValueOptions"
                    :key="item.dicKey"
                    :label="item.dicValue"
                    :value="item.dicValue"
                  >
                  </el-option>
                </el-select>
              </template>
            </el-table-column>

            <el-table-column
              :show-overflow-tooltip="true"
              prop="exchangeRate"
              label="汇率"
              width="150"
            >
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.exchangeRate"
                  @blur="blurExchangeRate($event, scope.row)"
                  clearable
                >
                </el-input>
              </template>
            </el-table-column>

            <el-table-column
              :show-overflow-tooltip="true"
              prop="originalAmount"
              label="金额（原币）"
              width="150"
            >
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.originalAmount"
                  @blur="blurOriginalAmount($event, scope.row)"
                  clearable
                >
                </el-input>
              </template>
            </el-table-column>

            <el-table-column
              :show-overflow-tooltip="true"
              prop="standardAmount"
              label="金额（本位币）"
              width="150"
            >
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.standardAmount"
                  @input="inputStandardAmount(scope.row)"
                  @blur="blurStandardAmount($event, scope.row)"
                  clearable
                >
                </el-input>
              </template>
            </el-table-column>

            <el-table-column
              :show-overflow-tooltip="true"
              prop="dueDate"
              label="到期日期"
              width="150"
            >
              <template slot-scope="scope">
                <el-date-picker
                  v-model="scope.row.dueDate"
                  type="date"
                  placeholder="选择日期"
                  style="width: 100%"
                  value-format="timestamp"
                >
                </el-date-picker>
              </template>
            </el-table-column>

            <el-table-column
              :show-overflow-tooltip="true"
              prop="expectPayDate"
              label="预计付款日期"
              width="150"
            >
              <template slot-scope="scope">
                <el-date-picker
                  v-model="scope.row.expectPayDate"
                  type="date"
                  placeholder="请选择日期"
                  style="width: 100%"
                  value-format="timestamp"
                >
                </el-date-picker>
              </template>
            </el-table-column>

            <el-table-column
              :show-overflow-tooltip="true"
              prop="contactNatureValue"
              label="往来性质"
              width="200"
              align="right"
              header-align="left"
            >
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.contactNatureValue"
                  placeholder="请选择"
                  @change="changeContactNatureValue(scope.row)"
                >
                  <el-option
                    v-for="item in contactNatureValueOptions"
                    :key="item.dicKey"
                    :label="item.dicValue"
                    :value="item.dicValue"
                  >
                  </el-option>
                </el-select>
              </template>
            </el-table-column>

            <el-table-column
              :show-overflow-tooltip="true"
              prop="contactOrgName"
              label="往来单位"
              width="213"
            >
              <template slot-scope="scope">
                <el-input v-model="scope.row.contactOrgName" disabled>
                </el-input>
              </template>
            </el-table-column>

            <el-table-column
              :show-overflow-tooltip="true"
              prop="contactUserName"
              label="个人"
              width="150"
            >
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.contactUserName"
                  clearable
                  :placeholder="canInput ? '' : '请输入'"
                  :disabled="canInput"
                >
                </el-input>
              </template>
            </el-table-column>

            <el-table-column
              :show-overflow-tooltip="true"
              prop="remark"
              label="备注"
              width="150"
            >
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.remark"
                  placeholder="请输入"
                  clearable
                >
                </el-input>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </template>
    </el-group-title>
    <!-- </div> -->
  </div>
</template>

<script>
import { generateUUID } from "@/basa/utils";
import {
  qryPaymentDetailChangeDict,
  qryMoneyTypeDict,
  listTransactionPropertiesDict
} from "../api";
import { mapGetters } from "vuex";
export default {
  props: ["paymentDetails"],
  computed: {
    ...mapGetters(["getInvoicePurchase"])
  },
  watch: {
    paymentDetails: {
      handler(n) {
        this.tableData = n;
      }
    },
    getInvoicePurchase: {
      handler(value) {
        console.log("我是vuex传到款项明细中的数据哦", value);
        let computedAmount = 0;
        computedAmount = value.reduce(
          (total, currentValue) => {
            return Number(currentValue.amount)
              ? Number(Number(total) + Number(currentValue.amount))
              : Number(total);
          },
          0
        );
        this.payComputed = computedAmount.toFixed(2);
        console.log('发票清单合计',this.payComputed)
      },
      deep:true
    }
  },
  data() {
    return {
      form: {},
      tableData: [],
      selectVal: [],
      options: [
        {
          id: 324,
          name: "模拟数据"
        }
      ],
      changeValueOptions: [], //变动
      originalCurrencyValueOptions: [], //原币币种
      contactNatureValueOptions: [], //往来性质
      canInput: true, //单位:不可输入  个人:可输入
      modelComputed: 0, //实际应支付
      payComputed: 0 //发票清单
    };
  },
  methods: {
    // 往来性质---start
    listTransactionPropertiesDict() {
      listTransactionPropertiesDict({}).then(res => {
        console.log(res.data.data);
        this.contactNatureValueOptions = res.data.data;
      });
    },
    // 往来性质 --- end
    // 变动 start
    qryPaymentDetailChangeDict() {
      qryPaymentDetailChangeDict({}).then(res => {
        const { data } = res.data;
        this.changeValueOptions = data;
      });
    },
    changeVal(val) {
      this.$set(val, "changeKey", val.changeKey);
      this.$set(val, "changeVal", val.changeVal);
    },
    // 变动end
    // 原币start
    qryMoneyTypeDict() {
      qryMoneyTypeDict({}).then(res => {
        const { data } = res.data;
        this.originalCurrencyValueOptions = data;
      });
    },
    changeOriginalCurrency(val) {
      this.$set(val, "originalCurrencyKey", val.originalCurrencyKey);
      this.$set(val, "originalCurrencyValue", val.originalCurrencyValue);
    },
    // 原币end
    // 往来性质
    changeContactNatureValue(val) {
      this.canInput = val.contactNatureValue == "单位" ? true : false;
      this.$set(val, "contactNatureValue", val.contactNatureValue);
      this.$set(val, "contactNatureKey", val.contactNatureKey);
    },
    // 汇率
    blurExchangeRate(e, row) {
      if (isNaN(e.target.value * 1)) {
        row.exchangeRate = 1.0;
      } else {
        if (e.target.value * 1 < 0) {
          row.exchangeRate = 1.0;
        } else {
          row.exchangeRate = Number(row.exchangeRate).toFixed(4);
          let comStandardAmount =
            Number(row.exchangeRate) * Number(row.originalAmount); //金额（本位币）=金额（原币）* 汇率
          this.$set(row, "standardAmount", comStandardAmount.toFixed(2));
          this.computedInput();
        }
      }
    },
    // 金额（原币）不能小于0 数字
    blurOriginalAmount(e, row) {
      if (isNaN(e.target.value * 1)) {
        row.originalAmount = 0.0;
      } else {
        if (e.target.value * 1 < 0) {
          row.originalAmount = 0.0;
        } else {
          row.originalAmount = Number(row.originalAmount).toFixed(2);
          let comStandardAmount =
            Number(row.exchangeRate) * Number(row.originalAmount); //金额（本位币）=金额（原币）* 汇率
          this.$set(row, "standardAmount", comStandardAmount.toFixed(2));
          this.computedInput();
        }
      }
    },
    // 金额（本位币）
    inputStandardAmount() {
      this.computedInput();
    },
    computedInput() {
      let computedStandardAmount = 0;
      computedStandardAmount = this.tableData.reduce((total, currentValue) => {
        return Number(currentValue.standardAmount)
          ? Number(Number(total) + Number(currentValue.standardAmount))
          : Number(total);
      }, 0);
      this.modelComputed = computedStandardAmount.toFixed(2);
    },
    // 金额（本位币）失焦
    blurStandardAmount(e, row) {
      if (isNaN(e.target.value * 1)) {
        row.standardAmount = null;
      } else {
        if (e.target.value * 1 < 0) {
          row.standardAmount = null;
        } else {
          row.standardAmount = Number(row.standardAmount).toFixed(2);
        }
      }
    },

    // 新增行
    addLine() {
      // 原币币种
      const originalCurrencyValueObj = this.originalCurrencyValueOptions.find(
        e => e.dicValue == "人民币元"
      );
      // 变动
      const changeValueObj = this.changeValueOptions.find(
        e => e.dicValue == "实际应支付"
      );
      this.tableData.push({
        id: generateUUID(),
        changeValue: changeValueObj.dicValue, //变动
        changeKey: changeValueObj.dicKey, //变动key
        paymentNameValue: "", //款项名称
        paymentNameKey: "", //款项名称名称编码
        specialProjectValue: "", //专项项目
        specialProjectKey: "", //专项项目编码
        receivablePayableNo: "", //应收应付编号
        unWrittenOffOriginalAmount: "", //未核销金额（原币）
        originalCurrencyValue: originalCurrencyValueObj.dicValue, //原币币种
        originalCurrencyKey: originalCurrencyValueObj.dicKey, //原币币种编码
        exchangeRate: "1.0000", //汇率
        originalAmount: "0.00", //金额（原币）
        standardAmount: "", //金额（本位币）
        dueDate: "", //到期日期
        expectPayDate: "", //预计付款日期
        contactNatureValue: "", //往来性质
        contactNatureKey: "", //往来性质编码
        contactOrgName: "", //往来单位
        contactOrgId: "", //往来单位id
        contactUserName: "", //个人
        contactUserId: "", //个人id
        remark: "" //备注
      });
    },
    // 复制行
    copyLine() {
      if (this.selectVal.length <= 0) {
        this.$showErrorMessage("请至少选择一项");
        return;
      }
      this.tableData.push(
        ...this.selectVal.map((v, i) => ({
          id: generateUUID(),
          changeValue: "实际应支付",
          paymentNameValue: v.paymentNameValue, //款项名称
          paymentNameKey: v.paymentNameKey, //款项名称名称编码
          specialProjectValue: v.specialProjectValue, //专项项目
          specialProjectKey: v.specialProjectKey, //专项项目编码
          receivablePayableNo: v.receivablePayableNo, //应收应付编号
          unWrittenOffOriginalAmount: v.unWrittenOffOriginalAmount, //未核销金额（原币）
          originalCurrencyValue: v.originalCurrencyValue, //原币币种
          originalCurrencyKey: v.originalCurrencyKey, //原币币种编码
          exchangeRate: v.exchangeRate, //汇率
          originalAmount: v.originalAmount, //金额（原币）
          standardAmount: v.standardAmount, //金额（本位币）
          dueDate: v.dueDate, //到期日期
          expectPayDate: v.expectPayDate, //预计付款日期
          contactNatureValue: v.contactNatureValue, //往来性质
          contactNatureKey: v.contactNatureKey, //往来性质编码
          contactOrgName: v.contactOrgName, //往来单位
          contactOrgId: v.contactOrgId, //往来单位id
          contactUserName: v.contactUserName, //个人
          contactUserId: v.contactUserId, //个人id
          remark: v.remark //备注
        }))
      );
    },
    // 删除行
    deleteRow() {
      if (this.selectVal.length <= 0) {
        this.$showErrorMessage("请至少选择一项");
        return;
      }
      console.log("wo选中", this.selectVal);
      var that = this;
      // 拿到选中的数据；
      var val = this.selectVal;
      // 如果选中数据存在
      if (val) {
        // 将选中数据遍历
        val.forEach(function (item, index) {
          // 遍历源数据
          that.tableData.forEach(function (itemI, indexI) {
            // 如果选中数据跟元数据某一条标识相等，删除对应的源数据
            if (item.id & (item.id === itemI.id)) {
              that.tableData.splice(indexI, 1);
            }
          });
        });
      }
      // 清除选中状态
      this.$refs.tableList.clearSelection();
    },
    selectionLineChangeHandle(val) {
      this.selectVal = val;
    },
    must(obj) {
      const columnsLabel = [
        "变动",
        "款项名称",
        "原币币种",
        "汇率",
        "金额（原币）",
        "到期日期",
        "往来性质"
      ];
      if (columnsLabel.includes(obj.column.label)) {
        return "must";
      } else {
        return;
      }
    }
  },
  created() {
    // 往来性质
    this.listTransactionPropertiesDict();
    // 变动
    this.qryPaymentDetailChangeDict();
    // 原币
    this.qryMoneyTypeDict();
  }
};
</script>

<style lang="scss" scoped>
/deep/ .el-table th.must > .cell:before {
  content: "* ";
  color: #ff1818;
}
.pay-ment {
  margin-top: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
/deep/ .el-group-title .group-content {
  margin-top: 20px !important;
}
</style>
